<template>
  <div class="department-detail-container">
    <van-nav-bar
      :title="department?.name"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 科室信息卡片 -->
    <van-cell-group inset class="my-4">
      <van-cell title="科室类型" :value="department?.type === 'outpatient' ? '门诊' : '住院'" />
      <van-cell title="所属大科" :value="department?.parentName" />
      <van-cell title="科室位置" :value="department?.location" />
      <van-cell title="咨询电话" :value="department?.phone" is-link @click="handleCall" />
    </van-cell-group>

    <!-- 科室简介 -->
    <div class="section-block">
      <div class="section-title">科室简介</div>
      <div class="content-text">{{ department?.introduction }}</div>
    </div>

    <!-- 特色技术 -->
    <div class="section-block" v-if="department?.specialties?.length">
      <div class="section-title">特色技术</div>
      <van-cell-group inset>
        <van-cell 
          v-for="(specialty, index) in department?.specialties" 
          :key="index"
          :title="specialty"
        />
      </van-cell-group>
    </div>

    <!-- 常见疾病 -->
    <div class="section-block" v-if="department?.commonDiseases?.length">
      <div class="section-title">常见疾病</div>
      <div class="disease-tags">
        <van-tag
          v-for="disease in department?.commonDiseases"
          :key="disease"
          type="primary"
          plain
          class="mr-2 mb-2"
        >
          {{ disease }}
        </van-tag>
      </div>
    </div>

    <!-- 医生团队 -->
    <div class="section-block">
      <div class="section-title">医生团队</div>
      
      <!-- 医生筛选 -->
      <van-dropdown-menu>
        <van-dropdown-item v-model="filterTitle" :options="titleOptions" />
        <van-dropdown-item v-model="sortBy" :options="sortOptions" />
      </van-dropdown-menu>

      <!-- 医生列表 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell-group inset v-for="doctor in doctors" :key="doctor.id" class="doctor-card">
          <van-cell :center="true" :border="false">
            <template #icon>
              <van-image
                round
                width="60"
                height="60"
                :src="doctor.avatar"
                class="mr-3"
              />
            </template>
            <template #title>
              <div class="doctor-name">{{ doctor.name }}</div>
              <div class="doctor-title text-sm text-gray-500">{{ doctor.title }}</div>
            </template>
            <template #label>
              <div class="doctor-specialty text-sm mt-1">
                擅长：{{ doctor.specialty }}
              </div>
            </template>
            <template #right-icon>
              <van-button 
                type="primary" 
                size="small"
                @click="handleAppointment(doctor)"
              >
                预约
              </van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </van-list>
    </div>

    <!-- 出诊时间表 -->
    <van-action-sheet v-model="showSchedule" :title="`${selectedDoctor?.name} 出诊时间`">
      <div class="schedule-content p-4">
        <van-calendar
          :show-title="false"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="calendarFormatter"
          @select="onDateSelect"
        />
      </div>
    </van-action-sheet>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { getDepartmentDetail, getDoctors } from '../api'

const router = useRouter()
const route = useRoute()
const department = ref(null)
const doctors = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 筛选相关
const filterTitle = ref('all')
const sortBy = ref('recommended')
const titleOptions = [
  { text: '全部职称', value: 'all' },
  { text: '主任医师', value: 'chief' },
  { text: '副主任医师', value: 'associate_chief' },
  { text: '主治医师', value: 'attending' },
  { text: '住院医师', value: 'resident' }
]
const sortOptions = [
  { text: '推荐排序', value: 'recommended' },
  { text: '职称排序', value: 'title' },
  { text: '预约量优先', value: 'appointments' }
]

// 出诊时间相关
const showSchedule = ref(false)
const selectedDoctor = ref(null)
const minDate = new Date()
const maxDate = new Date()
maxDate.setDate(maxDate.getDate() + 14) // 可预约未来14天

// 加载科室详情
const loadDepartmentDetail = async () => {
  try {
    const res = await getDepartmentDetail(route.params.id)
    department.value = res
  } catch (error) {
    console.error('获取科室详情失败：', error)
    showToast('获取科室详情失败')
  }
}

// 加载医生列表
const loadDoctors = async () => {
  try {
    const res = await getDoctors({
      departmentId: route.params.id,
      page: currentPage.value,
      size: pageSize,
      title: filterTitle.value === 'all' ? undefined : filterTitle.value,
      sort: sortBy.value
    })
    
    doctors.value.push(...res.content)
    loading.value = false
    
    if (res.content.length < pageSize) {
      finished.value = true
    } else {
      currentPage.value += 1
    }
  } catch (error) {
    console.error('获取医生列表失败：', error)
    showToast('获取医生列表失败')
    loading.value = false
  }
}

// 处理加载更多
const onLoad = () => {
  loadDoctors()
}

// 处理预约
const handleAppointment = (doctor) => {
  selectedDoctor.value = doctor
  showSchedule.value = true
}

// 处理日期选择
const onDateSelect = (date) => {
  showSchedule.value = false
  router.push({
    path: '/registration',
    query: {
      departmentId: department.value.id,
      doctorId: selectedDoctor.value.id,
      date: formatDate(date)
    }
  })
}

// 处理电话咨询
const handleCall = () => {
  if (!department.value?.phone) return
  window.location.href = `tel:${department.value.phone}`
}

// 日历格式化
const calendarFormatter = (day) => {
  // TODO: 根据医生排班信息处理可预约日期
  return day
}

// 工具函数
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

onMounted(() => {
  loadDepartmentDetail()
  loadDoctors()
})
</script>

<style scoped>
.department-detail-container {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: 20px;
}

.section-block {
  margin: 16px 0;
  background-color: #fff;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--van-text-color);
}

.content-text {
  font-size: 14px;
  line-height: 1.6;
  color: var(--van-text-color);
}

.disease-tags {
  display: flex;
  flex-wrap: wrap;
  padding: 8px;
}

.doctor-card {
  margin-bottom: 12px;
}

.doctor-name {
  font-size: 16px;
  font-weight: 500;
}

.doctor-title {
  margin-top: 4px;
}

.doctor-specialty {
  color: var(--van-text-color-2);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.schedule-content {
  height: 460px;
  overflow-y: auto;
}
</style> 